﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WorkList
{
    public class Code
    {
        private List<Marker> Markers;
        private DB database;                                    //экземпляр класса DB для обращения к БД
        private MySqlDataReader reader;                         //хранит в себе результат SQL-команды
        private List<string> dates;                             //хранит в себе все даты, встреченные в БД
        private int prevWeekDay = 0, prevWeekNumber = 0;
        private string prevMount = "";
        private Dictionary<string, int> MONTHtoCODE = new Dictionary<string, int>() 
        { 
            { "Jan" , 1 }, { "Feb", 2 }, { "Mar", 3 }, 
            { "Apr", 4 }, { "May", 5 }, { "Jun", 6 }, 
            { "Jul", 7 }, { "Aug", 8 }, { "Sep", 9 }, 
            { "Oct", 10 }, { "Nov", 11 }, { "Dec", 12 } 
        };
        private Dictionary<int, string> CODEtoMONTH = new Dictionary<int, string>()
            {
            { 1, "Jan" }, { 2, "Feb" }, { 3, "Mar" },
            { 4, "Apr" }, { 5, "May" }, { 6, "Jun" },
            { 7, "Jul" }, { 8, "Aug" }, { 9, "Sep" },
            { 10, "Oct" }, { 11, "Nov" }, { 12, "Dec" }
        };

        private int dayCounter = 0, HEIGHT = 200, WIDTH = 200;

        public int counter
        {
            get
            {
                return dayCounter;
            }
            set
            {
                if (value > 0) dayCounter = value;
            }
        }

        public Code()
        {
            database = new DB();
            dates = new List<string>();
            Markers = new List<Marker>();

            database.openConnection();
            reader = database.SelectAll();
        }

        public List<string[]> getReaderData()
        {
            List<string[]> data = new List<string[]>();
            for ( ; reader.Read(); )
            {
                string completed;
                try
                {
                    completed = reader.GetString("isCompleted");
                }
                catch(System.Data.SqlTypes.SqlNullValueException)
                {
                    completed = "NULL";
                }

                data.Add([reader.GetString("date").Substring(0, 10), reader.GetString("day"), reader.GetString("time")[0..5],
                    reader.GetString("name"), reader.GetString("discipline"), reader.GetString("grade"), completed]);
            }
            return data;
        }

        public PictureBox addPictureBox(string date)
        {
            if (prevMount != date[3..5])
            {
                prevMount = date[3..5];
                prevWeekDay = 0;
                prevWeekNumber = 0;
            }
            int dayNumber = Convert.ToInt16(date[0..2]);
            int weekDay = weekDaybyDate(date);
            PictureBox pBox = new PictureBox();

            int column = weekDay - 1;
            if (column < 0) column += 7;

            int weekNumber = prevWeekNumber + ( column < prevWeekDay ? 1 : 0);
            pBox.Location = new Point(WIDTH * column, 50 + HEIGHT * weekNumber);
            pBox.Size = new Size(WIDTH, HEIGHT);
            pBox.Image = Image.FromFile("C:\\Users\\antrelax\\source\\repos\\AntRelax\\WorkList\\WorkList\\Resources\\Закладка85.png");
            pBox.Name = "pBox";
            pBox.BackColor = Color.Transparent;
            pBox.BackgroundImageLayout = ImageLayout.Stretch;
            pBox.SizeMode = PictureBoxSizeMode.StretchImage;

            prevWeekDay = column;
            prevWeekNumber = weekNumber;

            return pBox;
        }

        int weekDaybyDate(string date)
        { //W = d + [ (13m - 1) / 5 ] + y + [ y / 4 ] + [ c / 4 ] - 2c
            int d = Convert.ToInt16(date[0..2]);
            int m = (Convert.ToInt16(date[3..5]) - 2);
            if (m <= 0) m += 12;
            int y = Convert.ToInt16(date[8..]);
            int c = Convert.ToInt16(date[6..8]);

            return (d + ((13 * m - 1) / 5) + y + (y / 4) + (c / 4) - 2 * c) % 7;

        }

        void clearPanel(Panel panel)
        {
            panel.Controls.Clear();
        }

        public void changeMonth(string month, Panel where)
        {
            clearPanel(where);
            foreach (var mark in Markers)
            {
                if (Convert.ToInt16(mark.month) == MONTHtoCODE[month])
                {
                    where.Controls.Add(mark.pictureBox);
                }
            }
        }

        public bool findDate(string date)
        {
            return dates.Contains(date);
        }

        public void addDate(string date)
        {
            dates.Add(date);
        }

        public void addMarker(Marker mark)
        {
            Markers.Add(mark);
        }

        public string findFirstMonth()
        {
            if (Markers.Count > 0) return CODEtoMONTH[Convert.ToInt16(Markers[0].month)];
            else throw new Exception("Нет ни одной записи!");
        }

        public string findFirstYear()
        {
            if (Markers.Count > 0) return Markers[0].year;
            else throw new Exception("Нет ни одной записи!");
        }

        ~Code()
        {
            database.closeConnection();
        }
    }
}
